import store from '@/store/index.js';
export const ab2hex = (buffer) => {
	const hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function(bit) {
			return ("00" + bit.toString(16)).slice(-2);
		}
	);
	return hexArr.join("");
};
export const str_to_hex = (str) => {
	let newstr = ''
	const chineseRegex = /^[\u4e00-\u9fa5]+$/;
	// 匹配数字的正则表达式
	const englishRegex = /^[A-Za-z0-9]+$/;
	for (let i = 0; i < str.length; i++) {
		if (englishRegex.test(str[i])) {
			newstr += "0x" + str.charCodeAt(i).toString(16).padStart(2, '0');
		} else if (chineseRegex.test(str[i])) {
			newstr += addPrefixToHex(utf8ToHexWithPrefix(str[i]))
		} else {
			newstr += "0x" + str.charCodeAt(i).toString(16).padStart(2, '0');
		}
	}
	return newstr

}
export const utf8ToHexWithPrefix = (str) => {
	return encodeURIComponent(str).replace(/%/g, "");
}
export const addPrefixToHex = (str) => {
	let result = '';
	for (let i = 0; i < str.length; i += 2) {
		result += '0x' + str.substr(i, 2);
	}
	return result;
}
export const formatMacAddress = (mac) => {
	// 首先，确保MAC地址是12位十六进制数  
	if (mac.length !== 12) {
		throw new Error('MAC地址必须是12位十六进制数');
	}

	// 每两位之间插入一个冒号  
	let formattedMac = '';
	for (let i = 0; i < mac.length; i += 2) {
		formattedMac += mac.substr(i, 2).toUpperCase() + (i < mac.length - 2 ? ':' : '');
	}

	return formattedMac;
};
export const ut_fn_time16 = (time) => {
	let w = "";
	let ntime = ut_fn_formatDate(time)[1];
	ntime[0] = `${ntime[0]}`.slice(2);
	ntime.length = 6
	for (let i in ntime) {
		w += ut_to16(`${parseInt(ntime[i])}`)
	}
	w += ut_to16(ut_fn_formatDate(time)[3])
	return w
};
//转16进制
export const ut_to16 = (str) => {
	str = parseInt(str).toString(16);
	str = str.length == 1 ? "0" + str : str;
	return "0x" + str;
};
export const ut_fn_week = (date, flag) => {
	var week;
	if (flag) {
		week = date.getDay()
		week = parseInt(week)
		if (week == 0) week = 7
	} else {
		if (date.getDay() == 0) week = "星期日"
		if (date.getDay() == 1) week = "星期一"
		if (date.getDay() == 2) week = "星期二"
		if (date.getDay() == 3) week = "星期三"
		if (date.getDay() == 4) week = "星期四"
		if (date.getDay() == 5) week = "星期五"
		if (date.getDay() == 6) week = "星期六"
	}

	return week;
};
//时间戳转日期
export const ut_fn_formatDate = (date, i = 0) => {
	var date = new Date(date);
	var YY = date.getFullYear();
	var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
	var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
	var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
	var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
	var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
	if (i == 0) {
		return [
			[YY + '-' + MM + '-' + DD + " " + hh + ":" + mm + ":" + ss],
			[YY, MM, DD, hh, mm, ss, date.getDay()],
			[ut_fn_week(date)],
			[ut_fn_week(date, true)]
		];
	} else if (i == 1) {
		return [
			[YY + '-' + MM + '-' + DD],
			[YY, MM, DD, hh, mm, ss, date.getDay()],
			[ut_fn_week(date)],
			[ut_fn_week(date, true)]
		]
	}
};
// 初始化蓝牙模块
export const openBluetoothAdapter = () =>
	new Promise((resolve) => {
		uni.openBluetoothAdapter({
			success(res) {
				resolve(true);
			},
			fail(err) {
				if (err.code === 10001) {
					uni.showModal({
						content: '请打开蓝牙后重试',
						showCancel: false
					})
				} else {
					// 其他错误信息提示
					uni.showToast({
						title: err.errMsg,
						icon: 'none',
					});
				}
				resolve(false);
			},
		});

	});

let devNames = ["SmartBed", "SmartSofa", "SmartMtz"];
// 开始搜索蓝牙
export const startBluetoothDevicesDiscovery = async (macAddress) =>
	new Promise((resolve, reject) => {
		uni.startBluetoothDevicesDiscovery({
			success() {
				uni.onBluetoothDeviceFound((res) => {
					let devices = res.devices;
					if (devNames.indexOf(devices[0].name) != -1) {
						let deviceI = ab2hex(devices[0].advertisData)
						let deviceIdt = formatMacAddress(deviceI)
						if (deviceIdt === macAddress) {
							if (uni.getSystemInfoSync().platform == 'ios') {
								connectToBLEDevice(devices[0].deviceId);
								// uni.offBluetoothDeviceFound(); // 停止监听设备发现事件
								stopBluetoothDevicesDiscovery();
								resolve(true);
							}
							if (uni.getSystemInfoSync().platform == 'android') {
								connectToBLEDevice(devices[0].deviceId);
								// uni.offBluetoothDeviceFound(); // 停止监听设备发现事件
								stopBluetoothDevicesDiscovery();
								resolve(true);
							}



						}
					}


				});
			},
			fail(err) {
				console.log(err,'err')
				stopBluetoothDevicesDiscovery();
				reject(err);
			},
		});

	});
// 创建一个函数来连接蓝牙设备
function connectToBLEDevice(deviceId) {
	return new Promise((resolve, reject) => {
		uni.createBLEConnection({
			deviceId, // 设备的 MAC 地址  
			success(res) {
				uni.showToast({
					title: '蓝牙连接成功',
					icon: 'none',
				});
				store.commit('updateBLEConnectStatus', true);
				store.commit('updateBLECmac', deviceId);
				resolve(res); // 连接成功  
			},
			fail(err) {
				reject(err); // 连接失败  
			}
		});
	});
}

// 停止搜索蓝牙
export const stopBluetoothDevicesDiscovery = () =>
	new Promise((resolve) => {
		uni.stopBluetoothDevicesDiscovery({
			success() {
				resolve(true);
			},
			fail() {
				resolve(false);
			},
		});
	});
// 获取蓝牙设备所有服务
export const getBLEDeviceServices = (deviceId) =>
	new Promise((resolve) => {
		uni.getBLEDeviceServices({
			deviceId,
			success(res) {
				let targetUUID = "0000FFFF-0000-1000-8000-00805F9B34FB";
				const foundService = findServiceByUUID(res.services, targetUUID);
				if (foundService) {
					resolve(foundService);
				} else {
					console.log("没有找到指定的服务");
				}

			},
			fail(err) {
				resolve([]);
			},
		});
	});

function findServiceByUUID(services, targetUUID) {
	for (let i = 0; i < services.length; i++) {
		if (services[i].uuid === targetUUID) {
			return services[i]; // 返回第一个匹配的服务对象  
		}
	}
	return null; // 如果没有找到匹配的服务，返回 null  
}
// 获取蓝牙设备某个服务中所有特征值
export const getBLEDeviceCharacteristics = ({
		deviceId,
		serviceId,
		deviceName
	}) =>
	new Promise((resolve) => {
		uni.getBLEDeviceCharacteristics({
			deviceId,
			serviceId,
			success(res) {
				let targetUUID = "0000FF01-0000-1000-8000-00805F9B34FB";
				const foundCharacteristic = findServiceByUUID(res.characteristics, targetUUID);
				if (foundCharacteristic) {
					resolve(foundCharacteristic);
				} else {
					console.log("没有找到指定的特性");
				}
				return

			},
			fail(err) {
				resolve([]);
			},
		});
	});

export const sendToBLE = (deviceId, id, code = null, deviceOBj) => {
	return writeSmartMtz({
		id,
		code,
		deviceId,
	}).then((writeCode) => {
		return writeBLECharacteristicValue({
			...deviceOBj, // 注意这里修正了变量名  
			writeCode,
		});
	}).catch((error) => {
		// 在这里处理错误  
		console.error('BLE写入失败:', error);
		// 可以选择抛出错误或进行其他处理  
	});
}
export const ut_fn_getType = (obj) => {
	let type = typeof obj;
	if (type != "object") return type;
	return Object.prototype.toString
		.call(obj)
		.replace(/^\[object (\S+)\]$/, "$1")
		.toLowerCase();
};
export const writeSmartMtz = (device) => {
	// 返回一个Promise  
	return new Promise((resolve, reject) => {
		const {
			id,
			code,
			deviceId
		} = device;
		// wifi连接信息（这里应该是字符串，而不是对象属性）  
		const wifi = {
			name: "0x090x00", // wifi账号  
			password: "0x0d0x00", // wifi密码  
			link: "0x0c0x00", // 连接wifi  
			type: "0x4d0x00"
		};

		let Counts = 0;
		let writeCode = '';
		if (deviceId) {
			store.dispatch('setWifiNameLength');
			let deviceCounts = store.state.deviceCounts;
			Counts = deviceCounts - 1;

		}
		let hexString = Counts.toString(16);
		if (hexString.length < 2) {
			hexString = '0' + hexString;
		}
		switch (id) {
			case 1:
				writeCode = '0x000x000x100x00';
				break; // 连接监测带  
			case 2:
				writeCode = `${wifi.name}0x${hexString}0x${code?.wifinamelength}${code.hexCharname}`;
				break;
			case 3:
				writeCode = `${wifi.password}0x${hexString}0x${code?.wifinamelength}${code.hexCharname}`;
				break;
			case 4:
				writeCode = `${wifi.link}0x${hexString}0x00`;
				break;
			case 5:
				writeCode = `${wifi.type}0x${hexString}0x040x000x6b0x310x30`
				break;
			case 6:
				writeCode = `${wifi.type}0x${hexString}0x040x000x6b0x310x31`
				break;
			case 7:
				writeCode = `${wifi.type}0x${hexString}0x040x000x6b0x310x32`
				break;
			case 8:
				writeCode = `${wifi.type}0x${hexString}0x010x01`
				break;
		}
		setTimeout(() => {
			resolve(writeCode);
		}, 1000);

		// 如果出现错误，可以使用reject(error)来拒绝Promise  
	});
};
export const notifyBLECharacteristicValueChange = ({
		deviceId,
		serviceId,
		characteristicId,
	}) =>
	new Promise((resolve) => {
		uni.notifyBLECharacteristicValueChange({
			state: true, // 启用 notify 功能
			deviceId,
			serviceId,
			characteristicId,
			success(res) {
				resolve(true);
			},
			fail(err) {
				resolve(false);
			},
		});
	});
export const ab2hexNew = (buffer) => {
	const hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function(bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	hexArr.join('')
	const lastTwoChars = hexArr.join('').slice(-2);
	const decimalNumber = parseInt(lastTwoChars, 16);
	return decimalNumber
}
export const writeBLECharacteristicValue = ({
		deviceId,
		serviceId,
		characteristicId,
		writeCode,
	}) =>
	new Promise((resolve) => {
		let len = writeCode.length / 4;
		let bufferArr = writeCode.match(/[\da-f]{2}/gi).map(function(h) {
			return parseInt(h, 16);
		});
		if (len == 4) {
			bufferArr[4] = bufferArr[2] + bufferArr[3];
		}
		len = bufferArr.length;
		if (len < 20) {
			for (let i = 0; i < 20 - len; i++) {
				bufferArr[i + len] = 0;
			}
		}
		let typedArray = new Uint8Array(bufferArr);
		let buffer = typedArray.buffer;
		uni.writeBLECharacteristicValue({
			deviceId,
			serviceId,
			characteristicId,
			value: buffer,
			success(res) {
				console.log(res, '指令发送成功', 'bufferArr')
				resolve(true);
			},
			fail(err) {
				resolve(false);
			},
		});
	});
	
	// 断开与低功耗蓝牙设备的连接
	export const closeBLEConnection = (deviceId) =>
		new Promise((resolve) => {
			uni.closeBLEConnection({
				deviceId,
				success() {
					resolve(true);
					store.commit('resetDeviceCount', 0);
					store.commit('updateBLEConnectStatus', false);
					store.commit('updateBLECmac', null);
					// console.log('断开连接')
					// uni.closeBluetoothAdapter({
					// 	success: (res) => {
					// 	},
					// 	fail: (err) => {}
					// });
				},
				fail(err) {
					resolve(false);
				},
			});
		});
	
	
	
	